<?php

if_get('/address_units', function ()
{
    list(
        $inputs['name']
    ) = input_list(
        'name'
    );
    $inputs = array_filter($inputs, 'not_null');

    $address_units = dao('address_unit')->find_all_by_column($inputs);

    $address_slot_counts = dao('address_slot')->query_count_by_address_units_group_by_address_unit_id($address_units);

    return render('address_unit/list', [
        'address_units' => $address_units,
        'address_slot_counts' => $address_slot_counts,
    ]);
});

if_post('/address_units/delete/*', function ($address_unit_id)
{
    $address_unit = dao('address_unit')->find($address_unit_id);
    otherwise($address_unit->is_not_null(), 'address_unit not found');

    $address_slot_count = dao('address_slot')->query_count_by_address_unit($address_unit);
    otherwise($address_slot_count == 0, '还有地址槽在使用该地址单位');

    $address_unit->delete();

    return redirect('/address_units');
});
